import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:znmm/config/app_color.dart';
import 'package:provider/provider.dart';

import 'calendar_weekday_model.dart';
import 'calendar_carousel.dart';
import 'calendar_util.dart';
import 'calendar_provider_mag.dart';

class CalendarBottomView extends StatefulWidget {
  final Function(dynamic object) clickBack;
  final DateTime tDefDateTime;
  const CalendarBottomView(
      {Key? key, required this.clickBack, required this.tDefDateTime})
      : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _CalendarBottomViewState createState() => _CalendarBottomViewState();
}

class _CalendarBottomViewState extends State<CalendarBottomView>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  static final List<String> weekList = [
    "周一",
    "周二",
    "周三",
    "周四",
    "周五",
    "周六",
    "周日"
  ];
  late CalendarController _calendarController;

  // String strSelectDate = sprintf("%4d-%02d-%02d",
  //     [DateTime.now().year, DateTime.now().month, DateTime.now().day]);

  DateTime tSelDataTime = DateTime.now();
  DateTime tDefDateTime = DateTime.now();
  String strTopData = "";
  int _iCurPageRowCount = 5;

  @override
  void initState() {
    super.initState();
    _calendarController = CalendarController();

    tDefDateTime = widget.tDefDateTime;
    tSelDataTime = tDefDateTime;

    strTopData = '${tSelDataTime.year}年${tSelDataTime.month}月'; //年月

    Provider.of<CalendarProviderMag>(context, listen: false)
        .setSecondInitDate(tDefDateTime);

    //获取当前page行数
    var rowCount =
        CalendarUtil.getRowCount(tDefDateTime.year, tDefDateTime.month, 7);
    _iCurPageRowCount = rowCount;
    //print("rowCount:$rowCount");
  }

  @override
  void dispose() {
    //if (_calendarController.hasListeners)
    //this._calendarController.dispose();
    //this._calendarController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double fWidth = MediaQuery.of(context).size.width;

    SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(statusBarColor: Colors.transparent));

    var historyProvider = Provider.of<CalendarProviderMag>(context);

    double fHeight =
        38.0 * _iCurPageRowCount + 180 + 44; //lufei Global.paddingBottom
    if (fHeight > MediaQuery.of(context).size.height) {
      fHeight = MediaQuery.of(context).size.height - 10;
    }

    return Container(
      color: AppColor.background,
      height: fHeight,
      width: fWidth,
      margin: const EdgeInsets.fromLTRB(0, 15, 0, 10),
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.topCenter,
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  //pre page
                  InkWell(
                      child: const Icon(
                        Icons.arrow_back_ios_rounded,
                        color: Color(0xFFA2A8B3),
                        size: 18,
                      ),
                      onTap: () {
                        _calendarController.previousPage();
                      }),
                  const SizedBox(
                    width: 20,
                  ),
                  Consumer<CalendarProviderMag>(
                      builder: (context, CalendarProviderMag counter, _) {
                    tSelDataTime = counter.secondCurrentPageTime;
                    // String strLeft =
                    //     '${counter.secondCurrentPageTime.year}年${counter.secondCurrentPageTime.month}月${counter.secondCurrentPageTime.day}日';

                    return Text(
                      strTopData,
                      style: const TextStyle(
                          fontSize: 17, color: Color(0xFF2B3039)),
                      textAlign: TextAlign.center,
                    );
                  }),
                  const SizedBox(
                    width: 20,
                  ),
                  //next page
                  InkWell(
                      child: const Icon(
                        Icons.arrow_forward_ios,
                        color: Color(0xFFA2A8B3),
                        size: 18,
                      ),
                      onTap: () {
                        _calendarController.nextPage();
                      }),
                  //currentPageDate:
                ],
              ),
            ),
            //rili
            Consumer<CalendarProviderMag>(
                builder: (context, CalendarProviderMag counter, _) {
              double fScreenWidth = MediaQuery.of(context).size.width;
              return CalendarCarousel(
                  fScreenWidth: fScreenWidth,
                  calendarShow: CalendarShow.CalendarShowMonth,
                  tBgColor: const Color(0xFFFFFFFF),
                  startTime: DateTime(2000, 1, 1),
                  endTime: DateTime(2099, 1, 1),
                  currentPageTime: counter.secondCurrentPageTime,
                  calendarController: _calendarController,
                  fLeftPandingVal: 10,
                  weekdayHeader:
                      CalendarWeekdayModel(7, 30, builder: (int weekday) {
                    return Text(
                      weekList[weekday - 1],
                      style: const TextStyle(
                          fontSize: 12, color: Color(0xFFA2A8B3)),
                    );
                  }),
                  dayWidgetBuilder: (DateTime date, bool isLastMonthDay,
                      bool isNextMonthDay) {
                    bool isSame = date.year ==
                            Provider.of<CalendarProviderMag>(context,
                                    listen: false)
                                .secondCurrentPageTime
                                .year &&
                        date.month ==
                            Provider.of<CalendarProviderMag>(context,
                                    listen: false)
                                .secondCurrentPageTime
                                .month &&
                        date.day ==
                            Provider.of<CalendarProviderMag>(context,
                                    listen: false)
                                .secondCurrentPageTime
                                .day;
                    bool bIsGray = false; //灰色不能点的
                    if ((isLastMonthDay || isNextMonthDay)) {
                      bIsGray = true;
                      isSame = false;
                    }
                    bool bIsToday = false;
                    if (DateTime.now().year == date.year &&
                        DateTime.now().month == date.month &&
                        DateTime.now().day == date.day) {
                      bIsToday = true;
                    }

                    return InkWell(
                      child: Column(
                        children: <Widget>[
                          Container(
                              margin: const EdgeInsets.only(top: 4),
                              width: 32,
                              height: 32,
                              decoration: isSame
                                  ? BoxDecoration(
                                      shape: BoxShape.rectangle,
                                      borderRadius: BorderRadius.circular(6.0),
                                      color: Colors.blue,
                                    )
                                  : (bIsToday
                                      ? BoxDecoration(
                                          //背景
                                          color: const Color(0xFFFFFFFF),
                                          //设置四周圆角 角度
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(4.0)),
                                          //设置四周边框
                                          border: Border.all(
                                              width: 1, color: Colors.blue),
                                        )
                                      : null),
                              child: Center(
                                child: Text(
                                  date.day.toString(),
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: isSame
                                        ? const Color(0xFFFFFFFF)
                                        : (bIsGray
                                            ? const Color(0xFFA2A8B3)
                                            : (bIsToday
                                                ? Colors.blue
                                                : const Color(0xFF2B3039))),
                                  ),
                                ),
                              )),
                        ],
                      ),
                      //日期选中
                      onTap: () {
                        if (bIsGray) {
                        } else {
                          historyProvider.setSecondCurrentPageTime(date);
                          _calendarController.goToDate(dateTime: date);
                        }
                      },
                    );
                  },
                  currentPageDate: (DateTime pageTime) {
                    //historyProvider.setSecondCurrentPageTime(pageTime);
                    historyProvider.setSecondPageUpdate();
                    //print("pageTime : $pageTime");
                    strTopData = '${pageTime.year}年${pageTime.month}月'; //年月
                  },
                  currentPageRowCount: (int iRowCount) {
                    _iCurPageRowCount = iRowCount;
                  });
            }),
            const SizedBox(
              height: 5,
            ),
            appBar(context, (date) {
              //_calendarController.goToDate(dateTime: date);
              _calendarController.goToToday();
              historyProvider.setSecondCurrentPageTime(DateTime.now());
            }),
          ],
        ),
      ),
    );
  }

  //
  Widget appBar(
      BuildContext context, Function(DateTime date) selectedDateBack) {
    return SizedBox(
      //color: Colors.amber,
      height: 40,
      child: Consumer<CalendarProviderMag>(
          builder: (context, CalendarProviderMag counter, _) {
        bool bIsToday = false;

        if (DateTime.now().year == counter.secondCurrentPageTime.year &&
            DateTime.now().month == counter.secondCurrentPageTime.month &&
            DateTime.now().day == counter.secondCurrentPageTime.day) {
          bIsToday = true;
        }
        return Row(
          children: [
            const SizedBox(
              width: 30,
            ),
            Expanded(
                child: InkWell(
              onTap: () {
                selectedDateBack(DateTime.now());
              },
              child: Container(
                height: 38,
                width: 100,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  //color: SkinMgr.Golden,
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1,
                      color: !bIsToday ? Colors.blue : const Color(0xFFA2A8B3)),
                ),
                child: Text(
                  "回到今日", //回到今日
                  style: TextStyle(
                    color: !bIsToday ? Colors.blue : const Color(0xFFA2A8B3),
                    fontSize: 16,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ),
            )),
            const SizedBox(
              width: 40,
            ),
            Expanded(
                child: InkWell(
              onTap: () {
                String strTime =
                    DateUtil.formatDate(tSelDataTime, format: 'yyyy-MM-dd');
                DateTime dTime = DateTime.parse(strTime);
                widget.clickBack(dTime);

                Navigator.of(context).pop();
              },
              child: Container(
                height: 38,
                width: 100,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  //color: SkinMgr.Golden,
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(width: 1, color: Colors.blue),
                ),
                child: const Text(
                  "确定", //确定
                  style: TextStyle(
                    color: Colors.blue,
                    fontSize: 16,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ),
            )),
            const SizedBox(
              width: 30,
            ),
          ],
        );
      }),
    );
  }
}
